package netTracker;

/**
 * A thread to conduct playback. Wakes up playback threads periodically based on tempo.
 * @author David Cummings
 */

public class MaestroThread implements Runnable{
	/** Utility class with debug flag: */
	Util util = new Util(this, true);
	Object playbackLock;
	NetTracker netTracker;
	boolean playing;
	int currentRow;
	
	public MaestroThread(Object playbackLock, NetTracker netTracker){
		this.playbackLock = playbackLock;
		this.netTracker = netTracker;
	}
	
	public void run(){
		currentRow = 0;
		long rate = Util.mapTempoToDelay(netTracker.getTempo());
		playing = true;
		try{
			while(true){
				synchronized(this){
					wait();
				}
				while(playing){
					netTracker.highlightRow(currentRow, true);
					for(int i=0; i<netTracker.getNumTracks(); i++)
						new Thread(new PlaybackThread(netTracker, currentRow, i)).start();
					Thread.sleep(rate);
					netTracker.highlightRow(currentRow, false);
					currentRow++;
					currentRow %= netTracker.getNumCells();
				}
			}
		}catch(InterruptedException x){
			util.debug(x);
		}
	}
	
	public void stop(){
		playing = false;
	}
	
	public void play(){
		playing = true;
		synchronized(this){
			notifyAll();
		}
	}
}
